package com.ly.test.config;/**
 * Created by Administrator on 2017/1/17.
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * @author liuyi
 * @date 2017/01/17 19:25
 */
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(RestExceptionHandler.class);

    /**
     * 处理@RequestParam错误, 即参数不足
     * @return
     */
    @Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.error("ErrorCode.ARG_INVALID");
        return new ResponseEntity<Object>("", status);
    }

    /**
     * 处理500错误
     * @return
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        //log.error("got internal error : {}", ex);

        // 请求方式不支持
        if (ex instanceof HttpRequestMethodNotSupportedException) {
            logger.error("ErrorCode.REQUEST_METHOD_UNSUPPORTED");
            return new ResponseEntity<Object>("", status);
        }

        logger.error("ErrorCode.INTERNAL_ERROR");
        return new ResponseEntity<Object>("", status);
    }


    /**
     * 处理参数类型转换失败
     * @param request
     * @return
     */
    @Override
    protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.error("type mismatch");
        logger.error("ErrorCode.ARG_INVALID");
        return new ResponseEntity<Object>("", status);
    }
}
